/*******************************************************************************
 * Copyright 2020 huanggefan.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

/**
 * 字符串格式化
 * StrFormat("xxxx={0}-xxxx{1}", ["aa", "bb"]) => "xxxx=aa-xxxx=bb"
 * @return {string}
 */
function StrFormat(src, arguments) {
    let result = src;
    if (arguments.length < 1) {
        return result;
    }
    let data = arguments;
    if (arguments.length === 1 && typeof (arguments) === "object") {
        data = arguments;
    }
    for (let key in data) {
        let value = data[key];
        if (undefined !== value) {
            result = result.replace("{" + key + "}", value);
        }
    }
    return result;
}

/**
 * 设置cookies
 * SetCookie("authToken", "xxxx", 1200)
 */
function SetCookie(name, value, timeout) {
    let exp = new Date();
    exp.setTime(exp.getTime() + timeout);
    document.cookie = name + "=" + escape(encodeURIComponent(value)) + ";expires=" + exp.toUTCString();
}

/**
 * 获取cookies
 * GetCookie("authToken")
 * @return {string}
 */
function GetCookie(name) {
    let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    arr = document.cookie.match(reg);
    if (arr)
        return unescape(decodeURIComponent(arr[2]));
    else
        return "";
}

/**
 * 删除cookies
 * RemoveCookie("authToken")
 */
function RemoveCookie(name) {
    const exp = new Date();
    exp.setTime(exp.getTime() - 1);
    document.cookie = name + "=;expires=" + exp.toUTCString();
}

/**
 * 获取URL的路径
 * GetUrlRelativePath() => /aa/bb/cc
 * @return {string}
 */
function GetUrlRelativePath() {
    const url = document.location.toString();
    const arrUrl = url.split("//");

    const start = arrUrl[1].indexOf("/");
    let relUrl = arrUrl[1].substring(start);//stop省略，截取从start开始到结尾的所有字符

    if (relUrl.indexOf("?") !== -1) {
        relUrl = relUrl.split("?")[0];
    }
    return relUrl;
}

/**
 * 获取URL的参数
 * GetQueryString("aa") => 1
 * @return {string}
 */
function GetQueryString(name) {
    const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    let s = window.location.search.replace("?", "&");
    let h = window.location.hash.replace("#", "&");
    let query = s + h;
    const r = query.substr(1).match(reg);//search,查询？#后面的参数，并匹配正则
    if (r != null) {
        return decodeURI(r[2]);
    } else {
        return "";
    }
}

/**
 * Base64编码
 * Base64("aa") => "ImFhIg=="
 * @return {string}
 */
function Base64(str) {
    return window.btoa(unescape(encodeURIComponent(str)));
}

/**
 * Base64解码
 * Base64("ImFhIg==") => "aa"
 * @return {string}
 */
function UnBase64(str) {
    return decodeURIComponent(escape(window.atob(str)));
}

/**
 * 渲染Markdown
 * CompileMarkdown("# 1\n ## 2") => "....略"
 * @return {string}
 */
function CompileMarkdown(markdownContent) {
    hljs.initHighlightingOnLoad();
    marked.setOptions({
        gfm: true,
        tables: true,
        breaks: false,
        pedantic: false,
        sanitize: false,
        smartLists: false,
        smartypants: false,
        renderer: new marked.Renderer(),
        highlight: function (code, lang) {
            if (lang && hljs.getLanguage(lang)) {
                return hljs.highlight(lang, code, true).value;
            } else {
                return hljs.highlightAuto(code).value;
            }
        }
    });

    let markdownCompiledContent = marked(markdownContent);
    markdownCompiledContent = markdownCompiledContent.replace(
        /<pre>/g,
        '<pre class="hljs markdown-pre">'
    );
    markdownCompiledContent = markdownCompiledContent.replace(
        /<blockquote>/g,
        '<blockquote class="markdown-blockquote">'
    );

    return markdownCompiledContent
}

/**
 * 对象复制
 * DeepCopy(obj) => obj
 * @return {Object}
 */
function DeepCopy(obj) {
    if (typeof obj != 'object') {
        return obj;
    }
    let newObj = {};
    for (let attr in obj) {
        newObj[attr] = DeepCopy(obj[attr]);
    }
    return newObj;
}

/**
 * MD5
 * MD5(String) => String
 * @return {String}
 */
function MD5(s) {
    let crypto = require('crypto');
    let md5 = crypto.createHash('md5');
    return md5.update(s).digest('hex');
}

function XHR(method, schemes, host, path, payload) {
    let xhr = new XMLHttpRequest();
    let url = StrFormat("{0}://{1}{2}", [schemes, host, path]);
    try {
        xhr.open(method, url, false);
        xhr.send(payload);
    } catch (e) {
        return;
    }

    let responseCode = xhr.status;
    let responseBody = xhr.responseText;

    if (responseCode !== 200) {
        return;
    }

    let obj = {};
    try {
        obj = JSON.parse(responseBody)
    } catch (e) {
        return;
    }
    console.log(obj);
    return obj;
}

function LoadToken() {
    let cookie = GetCookie(window.AuthTokenCookieName);
    window.AuthToken = cookie;
    try {
        let base64Info = UnBase64(cookie.split(".")[1]);
        window.AuthTokenInfo = JSON.parse(base64Info);
    } catch (e) {
    }
}

function CheckTokenExist() {
    let cookie = GetCookie(window.AuthTokenCookieName);
    if (cookie === "") {
        window.location.href = "/";
    }
    setTimeout(CheckTokenExist, 1000 * 10);
}

function ConfirmLeavePage() {
    window.onbeforeunload = function () {
        return "您确定要退出页面吗？系统不会保存您的数据。";
    }
}

module.exports = {
    StrFormat,
    SetCookie,
    GetCookie,
    RemoveCookie,
    GetUrlRelativePath,
    GetQueryString,
    Base64,
    UnBase64,
    CompileMarkdown,
    DeepCopy,
    MD5,
    XHR,
    LoadToken,
    CheckTokenExist,
    ConfirmLeavePage
};
